// 活动列表页面专用JavaScript

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    // 模拟活动数据
    const mockActivities = [
        {
            id: 1,
            title: "2023年校园科技节开幕式",
            category: "科技",
            image: "https://picsum.photos/id/1/800/450",
            date: "2023-10-15",
            time: "09:00-11:00",
            location: "中心体育场",
            organizer: "校学生会科技部",
            participants: 1258,
            status: "即将开始",
            tags: ["科技节", "开幕式", "大型活动"]
        },
        {
            id: 2,
            title: "大学生创新创业大赛宣讲会",
            category: "创业",
            image: "https://picsum.photos/id/20/800/450",
            date: "2023-10-18",
            time: "14:30-16:30",
            location: "学术报告中心",
            organizer: "就业指导中心",
            participants: 326,
            status: "报名中",
            tags: ["创业", "比赛", "就业"]
        },
        {
            id: 3,
            title: "校园秋季运动会",
            category: "体育",
            image: "https://picsum.photos/id/21/800/450",
            date: "2023-10-20",
            time: "全天",
            location: "田径场",
            organizer: "体育部",
            participants: 856,
            status: "即将开始",
            tags: ["体育", "运动会", "竞技"]
        },
        {
            id: 4,
            title: "校园歌手大赛决赛",
            category: "文艺",
            image: "https://picsum.photos/id/96/800/450",
            date: "2023-10-22",
            time: "19:00-21:30",
            location: "音乐厅",
            organizer: "校学生会文艺部",
            participants: 1024,
            status: "已结束",
            tags: ["音乐", "比赛", "文艺"]
        },
        {
            id: 5,
            title: "考研经验交流会",
            category: "学习",
            image: "https://picsum.photos/id/24/800/450",
            date: "2023-10-25",
            time: "15:00-17:00",
            location: "图书馆报告厅",
            organizer: "研究生院",
            participants: 678,
            status: "报名中",
            tags: ["考研", "学习", "交流"]
        },
        {
            id: 6,
            title: "校园招聘会",
            category: "就业",
            image: "https://picsum.photos/id/28/800/450",
            date: "2023-10-28",
            time: "09:00-15:00",
            location: "体育馆",
            organizer: "就业指导中心",
            participants: 2345,
            status: "即将开始",
            tags: ["就业", "招聘", "实习"]
        },
        {
            id: 7,
            title: "校园书法展",
            category: "文艺",
            image: "https://picsum.photos/id/36/800/450",
            date: "2023-10-30",
            time: "10:00-17:00",
            location: "艺术馆",
            organizer: "书法协会",
            participants: 421,
            status: "即将开始",
            tags: ["书法", "艺术", "展览"]
        },
        {
            id: 8,
            title: "AI技术讲座",
            category: "科技",
            image: "https://picsum.photos/id/42/800/450",
            date: "2023-11-02",
            time: "14:00-16:00",
            location: "计算机学院会议室",
            organizer: "计算机学院",
            participants: 289,
            status: "报名中",
            tags: ["AI", "技术", "讲座"]
        }
    ];

    // 当前筛选条件
    let currentFilters = {
        category: 'all',
        status: 'all',
        searchTerm: '',
        sortBy: 'latest',
        page: 1,
        pageSize: 4
    };

    // 活动容器
    const activityContainer = document.getElementById('activityList');
    // 分页容器
    const paginationContainer = document.getElementById('pagination');
    // 搜索框
    const searchInput = document.getElementById('activitySearch');
    // 分类筛选
    const categoryFilters = document.querySelectorAll('.category-filter');
    // 状态筛选
    const statusFilters = document.querySelectorAll('.status-filter');
    // 排序下拉框
    const sortSelect = document.getElementById('sortActivities');
    // 结果统计
    const resultCount = document.getElementById('resultCount');

    // 初始化页面
    initActivities();

    // 初始化活动列表
    function initActivities() {
        // 绑定事件监听器
        bindEventListeners();
        // 渲染活动列表
        renderActivities();
    }

    // 绑定事件监听器
    function bindEventListeners() {
        // 搜索框事件
        if (searchInput) {
            searchInput.addEventListener('input', function() {
                currentFilters.searchTerm = this.value.trim().toLowerCase();
                currentFilters.page = 1; // 重置到第一页
                renderActivities();
            });
        }

        // 分类筛选事件
        categoryFilters.forEach(filter => {
            filter.addEventListener('click', function() {
                // 更新选中状态
                categoryFilters.forEach(f => f.classList.remove('bg-primary', 'text-white'));
                this.classList.add('bg-primary', 'text-white');
                
                // 更新筛选条件
                currentFilters.category = this.getAttribute('data-category');
                currentFilters.page = 1; // 重置到第一页
                renderActivities();
            });
        });

        // 状态筛选事件
        statusFilters.forEach(filter => {
            filter.addEventListener('click', function() {
                // 更新选中状态
                statusFilters.forEach(f => f.classList.remove('bg-primary', 'text-white'));
                this.classList.add('bg-primary', 'text-white');
                
                // 更新筛选条件
                currentFilters.status = this.getAttribute('data-status');
                currentFilters.page = 1; // 重置到第一页
                renderActivities();
            });
        });

        // 排序事件
        if (sortSelect) {
            sortSelect.addEventListener('change', function() {
                currentFilters.sortBy = this.value;
                renderActivities();
            });
        }
    }

    // 筛选活动
    function filterActivities(activities) {
        return activities.filter(activity => {
            // 分类筛选
            if (currentFilters.category !== 'all' && activity.category !== currentFilters.category) {
                return false;
            }
            
            // 状态筛选
            if (currentFilters.status !== 'all' && activity.status !== currentFilters.status) {
                return false;
            }
            
            // 搜索筛选
            if (currentFilters.searchTerm) {
                const searchTerm = currentFilters.searchTerm;
                return activity.title.toLowerCase().includes(searchTerm) ||
                       activity.organizer.toLowerCase().includes(searchTerm) ||
                       activity.location.toLowerCase().includes(searchTerm) ||
                       activity.tags.some(tag => tag.toLowerCase().includes(searchTerm));
            }
            
            return true;
        });
    }

    // 排序活动
    function sortActivities(activities) {
        const sorted = [...activities];
        
        switch (currentFilters.sortBy) {
            case 'latest':
                return sorted.sort((a, b) => new Date(b.date) - new Date(a.date));
            case 'popular':
                return sorted.sort((a, b) => b.participants - a.participants);
            case 'title':
                return sorted.sort((a, b) => a.title.localeCompare(b.title));
            default:
                return sorted;
        }
    }

    // 分页活动
    function paginateActivities(activities) {
        const startIndex = (currentFilters.page - 1) * currentFilters.pageSize;
        const endIndex = startIndex + currentFilters.pageSize;
        return {
            items: activities.slice(startIndex, endIndex),
            total: activities.length,
            totalPages: Math.ceil(activities.length / currentFilters.pageSize)
        };
    }

    // 渲染活动列表
    function renderActivities() {
        // 应用筛选
        let filtered = filterActivities(mockActivities);
        // 应用排序
        let sorted = sortActivities(filtered);
        // 应用分页
        let paginated = paginateActivities(sorted);

        // 更新结果统计
        if (resultCount) {
            resultCount.textContent = `共找到 ${paginated.total} 个活动`;
        }

        // 清空活动容器
        if (activityContainer) {
            activityContainer.innerHTML = '';

            // 如果没有活动
            if (paginated.items.length === 0) {
                activityContainer.innerHTML = `
                    <div class="col-span-1 md:col-span-2 lg:col-span-3 text-center py-16">
                        <div class="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fa fa-search text-4xl text-gray-400"></i>
                        </div>
                        <h3 class="text-xl font-medium mb-2">没有找到符合条件的活动</h3>
                        <p class="text-gray-500">请尝试调整筛选条件或搜索关键词</p>
                        <button id="resetFilters" class="mt-4 btn-secondary">
                            重置筛选条件
                        </button>
                    </div>
                `;

                // 绑定重置按钮事件
                document.getElementById('resetFilters').addEventListener('click', function() {
                    resetFilters();
                });
            } else {
                // 渲染活动卡片
                paginated.items.forEach(activity => {
                    const card = document.createElement('div');
                    card.className = 'bg-white rounded-xl shadow-sm overflow-hidden activity-card transition-all duration-300';
                    card.innerHTML = `
                        <div class="relative">
                            <img src="${activity.image}" alt="${activity.title}" class="w-full h-48 object-cover">
                            <span class="absolute top-3 left-3 px-2 py-1 rounded-full text-xs font-medium ${getStatusClass(activity.status)}">
                                ${activity.status}
                            </span>
                            <div class="absolute bottom-3 left-3 flex flex-wrap gap-2">
                                ${activity.tags.slice(0, 2).map(tag => `
                                    <span class="px-2 py-1 bg-black/50 text-white text-xs rounded-full">
                                        ${tag}
                                    </span>
                                `).join('')}
                                ${activity.tags.length > 2 ? `
                                    <span class="px-2 py-1 bg-black/50 text-white text-xs rounded-full">
                                        +${activity.tags.length - 2}
                                    </span>
                                ` : ''}
                            </div>
                        </div>
                        <div class="p-5">
                            <h3 class="text-lg font-bold mb-2 line-clamp-1">${activity.title}</h3>
                            <div class="flex items-center text-sm text-gray-500 mb-3">
                                <span class="flex items-center mr-4">
                                    <i class="fa fa-user-o mr-1"></i>
                                    ${activity.organizer}
                                </span>
                                <span class="flex items-center">
                                    <i class="fa fa-map-marker mr-1"></i>
                                    ${activity.location}
                                </span>
                            </div>
                            <div class="flex flex-wrap gap-2 mb-4">
                                <span class="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full">
                                    ${activity.category}
                                </span>
                                <span class="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full">
                                    <i class="fa fa-calendar-o mr-1"></i>
                                    ${activity.date}
                                </span>
                                <span class="px-2 py-1 bg-gray-100 text-gray-600 text-xs rounded-full">
                                    <i class="fa fa-clock-o mr-1"></i>
                                    ${activity.time}
                                </span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="text-sm text-gray-500">
                                    <i class="fa fa-users mr-1"></i>
                                    已报名 ${window.formatNumber ? window.formatNumber(activity.participants) : activity.participants}
                                </span>
                                <button class="btn-primary text-sm">查看详情</button>
                            </div>
                        </div>
                    `;
                    activityContainer.appendChild(card);

                    // 绑定卡片点击事件（除了按钮）
                    card.addEventListener('click', function(e) {
                        if (!e.target.closest('button')) {
                            // 在实际应用中，这里应该跳转到活动详情页
                            console.log('查看活动详情:', activity.id);
                            alert(`查看活动详情: ${activity.title}`);
                        }
                    });
                });
            }
        }

        // 渲染分页
        renderPagination(paginated.totalPages);
    }

    // 获取状态对应的CSS类
    function getStatusClass(status) {
        switch (status) {
            case '即将开始':
                return 'bg-warning/90 text-white';
            case '报名中':
                return 'bg-primary text-white';
            case '进行中':
                return 'bg-success text-white';
            case '已结束':
                return 'bg-gray-400 text-white';
            default:
                return 'bg-gray-400 text-white';
        }
    }

    // 渲染分页
    function renderPagination(totalPages) {
        if (!paginationContainer) return;
        
        paginationContainer.innerHTML = '';
        
        // 只在有多个页面时显示分页
        if (totalPages <= 1) return;
        
        // 上一页
        const prevButton = document.createElement('button');
        prevButton.className = `px-4 py-2 rounded-lg transition-all ${currentFilters.page === 1 ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-white hover:bg-gray-50'}`;
        prevButton.innerHTML = '<i class="fa fa-angle-left mr-1"></i> 上一页';
        prevButton.disabled = currentFilters.page === 1;
        prevButton.addEventListener('click', function() {
            if (currentFilters.page > 1) {
                currentFilters.page--;
                renderActivities();
            }
        });
        paginationContainer.appendChild(prevButton);

        // 页码按钮
        const startPage = Math.max(1, currentFilters.page - 2);
        const endPage = Math.min(totalPages, startPage + 4);
        
        if (startPage > 1) {
            addPageButton(1);
            if (startPage > 2) {
                addEllipsis();
            }
        }
        
        for (let i = startPage; i <= endPage; i++) {
            addPageButton(i);
        }
        
        if (endPage < totalPages) {
            if (endPage < totalPages - 1) {
                addEllipsis();
            }
            addPageButton(totalPages);
        }

        // 下一页
        const nextButton = document.createElement('button');
        nextButton.className = `px-4 py-2 rounded-lg transition-all ${currentFilters.page === totalPages ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-white hover:bg-gray-50'}`;
        nextButton.innerHTML = '下一页 <i class="fa fa-angle-right ml-1"></i>';
        nextButton.disabled = currentFilters.page === totalPages;
        nextButton.addEventListener('click', function() {
            if (currentFilters.page < totalPages) {
                currentFilters.page++;
                renderActivities();
            }
        });
        paginationContainer.appendChild(nextButton);

        // 添加页码按钮的辅助函数
        function addPageButton(pageNum) {
            const button = document.createElement('button');
            button.className = `px-4 py-2 mx-1 rounded-lg transition-all ${pageNum === currentFilters.page ? 'bg-primary text-white font-medium' : 'bg-white hover:bg-gray-50'}`;
            button.textContent = pageNum;
            button.addEventListener('click', function() {
                currentFilters.page = pageNum;
                renderActivities();
            });
            paginationContainer.appendChild(button);
        }

        // 添加省略号的辅助函数
        function addEllipsis() {
            const ellipsis = document.createElement('span');
            ellipsis.className = 'px-2 py-2 text-gray-500';
            ellipsis.textContent = '...';
            paginationContainer.appendChild(ellipsis);
        }
    }

    // 重置筛选条件
    function resetFilters() {
        // 重置搜索框
        if (searchInput) {
            searchInput.value = '';
        }
        
        // 重置分类筛选
        categoryFilters.forEach(filter => {
            filter.classList.remove('bg-primary', 'text-white');
            if (filter.getAttribute('data-category') === 'all') {
                filter.classList.add('bg-primary', 'text-white');
            }
        });
        
        // 重置状态筛选
        statusFilters.forEach(filter => {
            filter.classList.remove('bg-primary', 'text-white');
            if (filter.getAttribute('data-status') === 'all') {
                filter.classList.add('bg-primary', 'text-white');
            }
        });
        
        // 重置排序
        if (sortSelect) {
            sortSelect.value = 'latest';
        }
        
        // 重置筛选对象
        currentFilters = {
            category: 'all',
            status: 'all',
            searchTerm: '',
            sortBy: 'latest',
            page: 1,
            pageSize: 4
        };
        
        // 重新渲染
        renderActivities();
    }
});